package com.aihna.mall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aihna.common.core.exception.ServiceException;
import com.aihna.common.core.utils.MapstructUtils;
import com.aihna.common.mybatis.core.page.TableDataInfo;
import com.aihna.common.mybatis.core.page.PageQuery;
import com.aihna.mall.enums.ProductSpuStatusEnum;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.aihna.mall.domain.bo.StoreProductBo;
import com.aihna.mall.domain.vo.StoreProductVo;
import com.aihna.mall.domain.StoreProduct;
import com.aihna.mall.mapper.StoreProductMapper;
import com.aihna.mall.service.IStoreProductService;
import com.aihna.common.core.utils.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 商品Service业务层处理
 *
 * @author Joseph.Chen
 * @date 2024-03-29
 */
@RequiredArgsConstructor
@Service
public class StoreProductServiceImpl implements IStoreProductService {

    private final StoreProductMapper baseMapper;

    /**
     * 查询商品
     */
    @Override
    public StoreProductVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询商品列表
     */
    @Override
    public TableDataInfo<StoreProductVo> queryPageList(StoreProductBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<StoreProduct> lqw = buildQueryWrapper(bo);
        Page<StoreProductVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询商品列表
     */
    @Override
    public List<StoreProductVo> queryList(StoreProductBo bo) {
        LambdaQueryWrapper<StoreProduct> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<StoreProduct> buildQueryWrapper(StoreProductBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<StoreProduct> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), StoreProduct::getName, bo.getName());
        lqw.eq(StringUtils.isNotBlank(bo.getCateId()), StoreProduct::getCateId, bo.getCateId());
        lqw.orderByDesc(StoreProduct::getSort);
        //关键字搜索
        if (StringUtils.isNotBlank(bo.getKeywords())) {
            lqw.and(i -> i
                    .or().like(StoreProduct::getName, bo.getKeywords())
                    .or().like(StoreProduct::getKeyword, bo.getKeywords()));
        }

        //类型搜索
        switch (bo.getTabType()) {
            case 1:
                //出售中（已上架）
                lqw.eq(StoreProduct::getIsShow, ProductSpuStatusEnum.ENABLE.getStatus());
                lqw.eq(StoreProduct::getIsRecycle, 0);
                break;
            case 2:
                //仓库中（未上架）
                lqw.eq(StoreProduct::getIsShow, ProductSpuStatusEnum.DISABLE.getStatus());
                lqw.eq(StoreProduct::getIsRecycle, 0);
                break;
            case 3:
                //已售罄
                lqw.eq(StoreProduct::getStock, 0);
                lqw.eq(StoreProduct::getIsRecycle, 0);
                break;
            case 4:
                //警戒库存
                lqw.le(StoreProduct::getStock, 10);
                lqw.eq(StoreProduct::getIsRecycle,0);
                break;
            case 5:
                //回收站
                lqw.eq(StoreProduct::getIsRecycle, ProductSpuStatusEnum.RECYCLE.getStatus());

                break;
            default:
                break;
        }

        return lqw;
    }

    /**
     * 新增商品
     */
    @Override
    public Boolean insertByBo(StoreProductBo bo) {
        StoreProduct add = MapstructUtils.convert(bo, StoreProduct.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改商品
     */
    @Override
    public Boolean updateByBo(StoreProductBo bo) {
        StoreProduct update = MapstructUtils.convert(bo, StoreProduct.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(StoreProduct entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除商品
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Map<Integer, Long> getTabsCount() {
        Map<Integer, Long> counts = Maps.newLinkedHashMapWithExpectedSize(5);

        for(int type = 1; type<=5; type++) {
            LambdaQueryWrapper<StoreProduct> lqw = new LambdaQueryWrapper<>();
            switch (type) {
                case 1:
                    //出售中（已上架）
                    lqw.eq(StoreProduct::getIsShow, ProductSpuStatusEnum.ENABLE.getStatus());
                    lqw.eq(StoreProduct::getIsRecycle, 0);
                    break;
                case 2:
                    //仓库中（未上架）
                    lqw.eq(StoreProduct::getIsShow, ProductSpuStatusEnum.DISABLE.getStatus());
                    lqw.eq(StoreProduct::getIsRecycle, 0);
                    break;
                case 3:
                    //已售罄
                    lqw.eq(StoreProduct::getStock, 0);
                    lqw.eq(StoreProduct::getIsRecycle, 0);
                    break;
                case 4:
                    //警戒库存
                    lqw.le(StoreProduct::getStock, 10);
                    lqw.eq(StoreProduct::getIsRecycle,0);
                    break;
                case 5:
                    //回收站
                    lqw.eq(StoreProduct::getIsRecycle, ProductSpuStatusEnum.RECYCLE.getStatus());

                    break;
                default:
                    break;
            }

            counts.put(type, baseMapper.selectCount(lqw));
        }

        return counts;
    }

    @Override
    public int updateStatus(Long id, Integer isShow) {
        return baseMapper.update(null,
                new LambdaUpdateWrapper<StoreProduct>()
                        .set(StoreProduct::getIsShow, isShow)
                        .eq(StoreProduct::getId, id));
    }

    @Override
    public boolean deleteProduct(Long[] ids, String type) {

        List<StoreProduct> storeProductList = baseMapper.selectBatchIds(Arrays.asList(ids));
        if (ObjectUtil.isNotNull(storeProductList) && storeProductList.size() > 0) {
            for (StoreProduct product : storeProductList) {
                if (ObjectUtil.isNull(product)) {
                    throw new ServiceException("商品不存在");
                }
                if (StrUtil.isNotBlank(type) && "recycle".equals(type) && ObjectUtil.equals(product.getDelFlag(), 1)) {
                    throw new ServiceException("商品已存在回收站");
                }

                LambdaUpdateWrapper<StoreProduct> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                if (StrUtil.isNotBlank(type) && "delete".equals(type)) {
                    // 判断商品活动状态(秒杀、砍价、拼团)
                    //isExistActivity(ids);

                    lambdaUpdateWrapper.eq(StoreProduct::getId, product.getId());
                    lambdaUpdateWrapper.set(StoreProduct::getDelFlag, 1);

                } else {
                    lambdaUpdateWrapper.eq(StoreProduct::getId, product.getId());
                    lambdaUpdateWrapper.set(StoreProduct::getIsRecycle, 1);
                }

                int status = baseMapper.update(lambdaUpdateWrapper);

                if (ObjectUtil.equals(status, 0)) {
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public boolean reStoreProduct(Long[] ids) {
        LambdaUpdateWrapper<StoreProduct> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        for (Long id : ids) {
            lambdaUpdateWrapper.eq(StoreProduct::getId, id);
            lambdaUpdateWrapper.set(StoreProduct::getIsRecycle, 0);
            int status = baseMapper.update(lambdaUpdateWrapper);
            if (ObjectUtil.equals(status, 0)) {
                return false;
            }
        }

        return true;
    }


}
